#!/bin/sh
#
# autodeploy -- deploy some labs automatically
#
# Copyright (C) 2016-2020 Wu Zhangjin <lzufalcon@163.com>
#

uname | grep -q MINGW && PWD_OPT="-W"
TOP_DIR="$(cd "$(dirname "$0")"/../../ && pwd $PWD_OPT)"
. "$TOP_DIR"/tools/docker/config $* >/dev/null

[ "x$HOST_OS" != "xLinux" ] && echo "LOG: Only available for Linux currently." && exit 1

DST=/usr/local/bin/cloud-lab-autodeploy
SRC=$TOP_DIR/tools/deploy/batch
CRON=/etc/cron.hourly/0cloud-lab
LOG=/var/log/cloud-lab.autodeploy.log
LOCK=/var/lock/cloud-lab.autodeploy.lock
WAIT=3600

[ -z "$loop" ] && loop=1
[ -z "$interval" ] && interval="10s"
[ -z "$alive" ] && alive="30m"
[ -z "$cleanup" ] && cleanup=1
[ -z "$peruser" ] && peruser=1
[ -z "$labs" ] && labs="linux-0.11-lab cs630-qemu-lab"
[ -z "$prompt" ] && prompt="<em>说明</em>：以下帐号仅供免费体验，半小时更新一组。"
[ -z "$empty_prompt" ] && empty_prompt="<em>说明</em>：下一组免费体验帐号即将放出，请稍等片刻。"

[ `id -u` -ne 0 ] && SUDO=sudo

echo "LOG: create cron tasks"

$SUDO touch $LOG
$SUDO chown $HOST_USER:$HOST_USER $LOG

$SUDO /bin/bash -c "cat <<EOF > $DST
#!/bin/bash

sudo -u $HOST_USER \\\\
    peruser=$peruser loop=$loop interval=$interval alive=$alive cleanup=$cleanup \\\\
    labs='$labs' \\\\
    prompt='$prompt' \\\\
    empty_prompt='$empty_prompt' \\\\
    $SRC \\\\
    | tee $LOG
EOF"

$SUDO /bin/bash -c "cat <<EOF > $CRON
#!/bin/bash

# Clean up the log file every hour
echo > $LOG

flock -w $WAIT -x $LOCK -c $DST
EOF"

$SUDO chmod a+x $DST $CRON
$SUDO chmod o-r $LOG
$SUDO service cron restart
